import pygame
from gameworld import GW
from blocktype import BlockType
from game_event_manager import GameEventManager, GameEvent
import time

class Board:
    def __init__(self, res_manager=None):
        self.data = []
        self._init_data()
        self.score = 0

        self.pause_state = False

        if res_manager:
            self.image_dict = res_manager.image_dict
            self.bg_img = res_manager.board_bg
            self.bg_img = pygame.transform.scale(self.bg_img, (250, 500))

    def update(self, key_pressed):

        if key_pressed[pygame.K_SPACE]:
            print("pause")
            if self.pause_state == False:
                GameEventManager.post_event(GameEvent("GAME_PAUSE"))
                self.pause_state = True
                time.sleep(0.5)
            else:
                GameEventManager.post_event(GameEvent("GAME_RESUME"))
                self.pause_state = False
                time.sleep(0.2)

        # check if board is full
        for b in self.data[0]:
            if b != 0:
                GameEventManager.post_event(GameEvent("GAME_OVER"))
                # gameover_event = pygame.event.Event(GW.EVENT_GAMEOVER, message="Game Over")
                # pygame.event.post(gameover_event)
                return


        # check if a line is full
        full_line_list = []
        for i in range(19, -1, -1):
            is_full = [True,]
            for b in self.data[i]:
                if b == 0:
                    is_full[0] = False
                    break
            if is_full[0]:
                full_line_list.append(i)


        if len(full_line_list) == 0:
            return

        self.score += len(full_line_list) * 10
        se = GameEvent(GW.EVENT_SCORE_CHANGE)
        se.data = {"score": self.score}
        GameEventManager.post_event(se)
        # print(se.data)
        # print(f"Score {self.score}")

        for line in full_line_list:
            self.data.pop(line)

        for i in range(len(full_line_list)):
            self.data.insert(0, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])


    def draw(self, screen):
        self.draw_board(screen)

    def draw_board(self, screen):

        pygame.draw.rect(screen, (100, 255, 255),
                         (GW.BOARD_LEFT, GW.BOARD_TOP, 10 * GW.BLOCK_SIZE, 20 * GW.BLOCK_SIZE))
        screen.blit(self.bg_img, (GW.BOARD_LEFT, GW.BOARD_TOP))

        pygame.draw.rect(screen, (50, 80, 80),
                         (GW.BOARD_LEFT - 10, GW.BOARD_TOP - 10, 10 * GW.BLOCK_SIZE + 20, 20 * GW.BLOCK_SIZE + 20),
                         10, 10)

        for line in range(21):
            pygame.draw.line(screen, GW.COLOR_BLACK,
                             (GW.BOARD_LEFT, GW.BOARD_TOP + line * GW.BLOCK_SIZE),
                             (GW.BOARD_LEFT + 10 * GW.BLOCK_SIZE, GW.BOARD_TOP + line * GW.BLOCK_SIZE))
        for col in range(11):
            pygame.draw.line(screen, GW.COLOR_BLACK,
                             (GW.BOARD_LEFT + col * GW.BLOCK_SIZE, GW.BOARD_TOP),
                             (GW.BOARD_LEFT + col * GW.BLOCK_SIZE, GW.BOARD_TOP + 20 * GW.BLOCK_SIZE))

        for li,line in enumerate(self.data):
            for bi,b in enumerate(line):
                if b != 0 :
                    block_color = BlockType.colors.get(b)
                    pygame.draw.rect(screen, block_color,
                                     (GW.BOARD_LEFT + bi * GW.BLOCK_SIZE,
                                      GW.BOARD_TOP + li * GW.BLOCK_SIZE,
                                      GW.BLOCK_SIZE, GW.BLOCK_SIZE))
                    if self.image_dict:
                        block_img = self.image_dict.get(b)
                        screen.blit(block_img,
                                    (GW.BOARD_LEFT + bi * GW.BLOCK_SIZE,
                                     GW.BOARD_TOP + li * GW.BLOCK_SIZE)
                                    )

    def _init_data(self):
        for line in range(20):
            ln = []
            for column in range(10):
                ln.append(0)
            self.data.append(ln)

        # DEBUG
        # self.data[10][5] = 1
        # self.data[19][9] = 2

